<template>
  <el-dialog
    :visible.sync="dialog"
    :close-on-click-modal="false"
    :title="title"
    width="750px"
    :append-to-body="true"
    center
    @close="doClose"
  >
    <div class="main-container">
      <span class="baseInfo">
        <el-divider content-position="left"><el-tag size="mini">基础信息</el-tag></el-divider>
      </span>
      <el-form ref="editForm" :model="rule" :rules="rules" label-width="auto" size="mini">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规则组:" :required="editDisabled" prop="ruleGroupId">
              <el-select v-model="rule.ruleGroupId" placeholder="请选择" size="mini" style="width: 220px;" clearable :disabled="editDisabled">
                <el-option v-for="item in parent.ruleGroups" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则名称:" :required="editDisabled" prop="ruleName">
              <el-input v-model="rule.ruleName" size="mini" placeholder="请输入" :disabled="editDisabled" maxlength="128" show-word-limit style="width: 220px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规则描述:" prop="ruleDesc">
              <el-input v-model="rule.ruleDesc" type="textarea" maxlength="512" show-word-limit rows="1" size="mini" placeholder="请输入" :disabled="editDisabled" style="width: 220px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用:" prop="enableFlag">
              <el-switch
                v-model="enableFlag"
                style="font-size:12px;"
                :disabled="editDisabled"
                size="mini"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="config">
        <el-divider content-position="left"><el-tag size="mini">配置规则</el-tag></el-divider>
      </div>
      <ruleTree ref="ruleTree" :parent="currentObj" />
      <el-row v-if="!editDisabled" :gutter="20" style="margin-top:30px;">
        <el-col :span="24">
          <div style="text-align: right;">
            <el-button size="small" @click="doClose()">取消</el-button>
            <el-button type="primary" size="small" @click="doSave()">保存</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row v-else :gutter="20" style="margin-top:30px;">
        <el-col :span="24">
          <div style="text-align: right;">
            <el-button type="primary" size="small" @click="doClose()">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>
<script>
import { Message } from 'element-ui'
import { parseToString } from '@/utils/datefromat'
import { showNameByValue } from '@/utils/selectUtil'
import ruleTree from './rule-tree'
import { uuid } from '@/utils/uuid'
import Rule from './js/rule-rules'
import {
  findAllOperators,
  findAllDataTypeOperatorMappers,
  findAllMatchValueDataTypeMappers,
  findAllDataTypes,
  addOrUpdate,
  findRuleTreeByRuleId } from '@/api/coi/configuration/rule-config/rule'
import {
  getEmptyRule,
  getDefualtRootNode,
  getEmptyNode,
  getEmptyCondition,
  getEmptyVariableField } from './js/rule-tree'

export default {
  components: { ruleTree },
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialog: false,
      loading: false,
      currentObj: this,
      title: '',
      rules: {},
      operators: [],
      dataTypes: [],
      dataTypeOperatorMap: {},
      matchValueDataTypeMap: {},
      rule: this.getEmptyRule(),
      treeData: [],
      nodeTypeData: 'DATA',
      nodeTypeAnd: 'AND',
      nodeTypeOr: 'OR',
      baseUrl: window.appConfig.coiBuyerConfigBaseUrl,
      editDisabled: false,
      ruleValidate: new Rule(this)
    }
  },
  computed: {
    showSaveButton: function() {
      return !this.rule.id
    },
    enableFlag: {
      get: function() {
        return this.rule && this.rule.enableFlag && this.rule.enableFlag === 1
      },
      set: function(val) {
        if (this.rule) {
          console.log('enableFlag: set:' + val)
          if (val) {
            this.rule.enableFlag = 1
          } else {
            this.rule.enableFlag = 0
          }
        }
      }
    }
  },
  created() {
    this.$nextTick(() => {
    })
  },
  mounted() {
    this.$nextTick(() => {
      this.init()
      this.ruleValidate.initRules()
    })
  },
  methods: {
    uuid,
    getEmptyRule,
    getDefualtRootNode,
    getEmptyNode,
    getEmptyCondition,
    getEmptyVariableField,
    showNameByValue,
    parseToString,
    init() {
      var _this = this
      findAllOperators(this.baseUrl).then(res => {
        if (res) {
          _this.operators = res.result
        }
      })
      findAllDataTypes(this.baseUrl).then(res => {
        if (res) {
          _this.dataTypes = res.result
        }
      })
      findAllDataTypeOperatorMappers(this.baseUrl).then(res => {
        if (res && res.result) {
          console.log('findAllDataTypeOperatorMappers')
          res.result.forEach(item => {
            if (item.dataType) {
              _this.dataTypeOperatorMap[item.dataType] = item.operators
            }
          })
        }
      })
      findAllMatchValueDataTypeMappers(this.baseUrl).then(res => {
        if (res && res.result) {
          console.log('findAllMatchValueDataTypeMappers')
          res.result.forEach(item => {
            if (item.dataType) {
              _this.matchValueDataTypeMap[item.dataType] = item.dataTypes
            }
          })
        }
      })
    },
    initRuleTree() {
      var data = []
      this.rule = this.getEmptyRule()
      this.rule.node.uuid = this.uuid()
      data.push(this.rule.node)
      this.treeData = data
    },
    getRuleTreeByRuleId(val) {
      console.log('getRuleTreeByRuleId:' + val)
      var self = this
      findRuleTreeByRuleId(this.baseUrl, val).then(res => {
        var data = []
        if (res && res.result && res.result.node) {
          console.log('findRuleTreeByRuleId:' + val)
          self.rule = res.result
          if (!res.result.node.nodeLevel) {
            res.result.node.nodeLevel = 0
          }
          self.setUUID(res.result.node)
          data.push(res.result.node)
          self.treeData = data
        } else {
          self.rule = self.getEmptyRule()
          self.rule.ruleGroupId = val
          self.rule.node.uuid = self.uuid()
          data.push(self.rule.node)
          self.treeData = data
        }
      })
    },
    setUUID(node) {
      if (node) {
        node.uuid = this.uuid()
        if (node.children && node.children.length && node.children.length > 0) {
          for (var i = 0; i < node.children.length; i++) {
            // node.children[i].parent = node
            if (!node.children[i].nodeLevel) {
              node.children[i].nodeLevel = node.nodeLevel + 1
            }
            this.setUUID(node.children[i])
          }
        }
      }
    },
    // 用于替换节点的parent/dataTypeOperators，避免JSON.stringify循环依赖错误问题/过滤不必要的数据提交到后台
    replacement(key, value) {
      if (key === 'parent') {
        return null
      }
      if (key === 'dataTypeOperators') {
        return null
      }
      if (key === 'variableField') {
        return null
      }
      return value
    },
    // 关闭
    doClose() {
      this.dialog = false
      this.rule = this.getEmptyRule()
      this.$refs.editForm.clearValidate()
    },
    // 保存
    doSave() {
      var _this = this
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm('确认保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            _this.loading = true
            var json = JSON.stringify(this.rule, this.replacement)
            var copyRule = JSON.parse(json)
            addOrUpdate(this.baseUrl, copyRule).then(res => {
              if (res) {
                Message({
                  message: res.result,
                  type: 'success',
                  duration: 2 * 1000
                })
                _this.doClose()
                _this.parent.toQuery()
              }
            }, err => {
              console.log(err)
            })
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.field-divider >>> .el-divider--horizontal {
  margin: 5px 0px;
}
.container >>> .el-tabs__content{
  padding-left: 0px;
}
.config >>> .el-divider--horizontal {
  margin: 0px;
  margin-top: 5px;
  margin-bottom: 25px;
}
.baseInfo >>> .el-divider--horizontal {
  margin: 0px;
  margin-top: 0px;
  margin-bottom: 25px;
}
.el-dialog__body {
  padding: 0px 20px;
}
</style>
